package org.springblade.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.exception.TrainingServiceException;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.personal.entity.UserBaseEntity;
import org.springblade.modules.personal.entity.UserTeacherEntity;
import org.springblade.modules.personal.service.IUserBaseService;
import org.springblade.modules.personal.service.IUserTeacherService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.springblade.core.cache.constant.CacheConstant.USER_CACHE;
import static org.springblade.modules.system.controller.RoleController.TRAINNER_ROLE_NAME;

@NonDS
@RestController
@RequestMapping("blade-user/teacher")
@AllArgsConstructor
@Api(value = "教师管理", tags = "教师管理")
public class TeacherController {

	private final IUserService userService;
	private final IUserBaseService userBaseService;
	private final IRoleService roleService;
	private final IUserTeacherService userTeacherService;
	/**
	 * 查询单条
	 */
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "查看详情", notes = "传入id")
	@GetMapping("/detail")
	public R<UserVO> detail(User user) {
		User detail = userService.getOne(Condition.getQueryWrapper(user));
		UserVO userVO = UserWrapper.build().entityVO(detail);
		UserBaseEntity userBaseEntity = userBaseService.selectByUserId(userVO.getId());
		if (null != userBaseEntity) {
			userVO.setIdCard(userBaseEntity.getUserNumber());
			userVO.setUserName(userBaseEntity.getUserName());
			userVO.setTrainingMajorCategory(userBaseEntity.getTrainingMajorCategory());
			userVO.setTrainingMajorDirection(userBaseEntity.getTrainingMajorDirection());
			userVO.setAppointmentGrade(userBaseEntity.getAppointmentGrade());
			userVO.setRemark(userBaseEntity.getRemark());
		}
		return R.data(userVO);
	}


	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入User")
	@Transactional(rollbackFor = Exception.class)
	public R update(@Valid @RequestBody UserVO user) {
		if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(user.getRoleId())) {
			List<Long> sanYuanRoldIds = roleService.getSanYuanRoldIds();
			if (CollectionUtil.isNotEmpty(sanYuanRoldIds)) {
				int num=0;
				for (Long sanYuanId:sanYuanRoldIds){
					if(user.getRoleId().contains(sanYuanId.toString()) )num++;
				}
				if (num>1){
					throw new TrainingServiceException("不能把两个及以上的三员角色同时分配给一个用户");
				}
			}
		}
		CacheUtil.clear(USER_CACHE);
		//修改user
		userService.updateUser(user);

		//修改userBase
		LambdaUpdateWrapper<UserBaseEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
		lambdaUpdateWrapper.eq(UserBaseEntity::getUserId, user.getId());
		lambdaUpdateWrapper.set(UserBaseEntity::getTrainingMajorCategory, user.getTrainingMajorCategory());
		lambdaUpdateWrapper.set(UserBaseEntity::getTrainingMajorDirection, user.getTrainingMajorDirection());
		lambdaUpdateWrapper.set(UserBaseEntity::getAppointmentGrade, user.getAppointmentGrade());
		lambdaUpdateWrapper.set(UserBaseEntity::getRemark, user.getRemark());

		return R.status(userBaseService.update(lambdaUpdateWrapper));
	}

	/**
	 * 删除教师身份，并非删除人员
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "删除", notes = "传入ids集合")
	@Transactional(rollbackFor = Exception.class)
	public R remove(@RequestParam String ids) {
		//获取老师的roleId
		List<Long> teacherRoleIds = roleService.getRoleIdsByLikeRoleName("师");

		List<String> userNewRole = new ArrayList<>();
		List<Long> userIds = Func.toLongList(ids);

		//删除教师相关角色
		userIds.forEach(userId -> {
			User user = userService.getById(userId);
			List<Long> userRoleList = Func.toLongList(user.getRoleId());
			userRoleList.forEach(role -> {
				//如果非教师相关的角色id
				if (!teacherRoleIds.contains(role)) userNewRole.add(role.toString());
			});

			String newRoleString = "";
			if (CollectionUtil.isNotEmpty(userNewRole)) {
				newRoleString = StringUtil.join(userNewRole, ",");//将列表转为成以逗号隔开的字符串
			} else {
				//如果没有任何角色，则给基础角色 受训人员的角色
				List<Long> trainner = roleService.getRoleIdsByLikeRoleName(TRAINNER_ROLE_NAME);
				newRoleString = StringUtil.join(trainner, ","); //将列表转为成以逗号隔开的字符串
			}
			user.setRoleId(newRoleString);
			//修改user
			userService.updateUser(user);
			userTeacherService.removeByUserId(userId);//删除教师身份
		});

		CacheUtil.clear(USER_CACHE);
		return R.status(true);
	}

	@GetMapping("/page-teacher")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "教师列表", notes = "传入account和realName")
	public R teacherPage(@ApiIgnore User user, Query query, Long deptId, BladeUser bladeUser) {
		List<UserTeacherEntity> userTeacherList = userTeacherService.list();
		if (CollectionUtil.isEmpty(userTeacherList)) return R.success("暂无数据");
		List<Long> teacherIds = userTeacherList.stream().map(UserTeacherEntity::getUserId).collect(Collectors.toList());
		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.in(User::getId,teacherIds);
		//搜索处理
		if (StringUtils.isNotBlank(user.getRealName())) {
				lambdaQueryWrapper.like(User::getRealName, user.getRealName());
		}

		if (StringUtils.isNotBlank(user.getAccount())) {
				lambdaQueryWrapper.like(User::getAccount, user.getAccount());
		}

		IPage<User> pages = userService.page(Condition.getPage(query), lambdaQueryWrapper);

		IPage<UserVO> userVOIPage = UserWrapper.build().pageVO(pages);
		userVOIPage.getRecords().forEach(userVo -> {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserId(userVo.getId());
			if (null != userBaseEntity) {
				userVo.setIdCard(userBaseEntity.getUserNumber());
				userVo.setUserName(userBaseEntity.getUserName());
				userVo.setTrainingMajorCategory(userBaseEntity.getTrainingMajorCategory());
				userVo.setTrainingMajorDirection(userBaseEntity.getTrainingMajorDirection());
				userVo.setAppointmentGrade(userBaseEntity.getAppointmentGrade());
				userVo.setRemark(userBaseEntity.getRemark());

			}
		});
		return R.data(userVOIPage);
	}



	@GetMapping("/page-not-teacher")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "账号名", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "realName", value = "姓名", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "获取非教师角色的人员列表", notes = "传入account和realName")
	public R notTeacherPage(@ApiIgnore User user, Query query, Long deptId, BladeUser bladeUser) {
		List<UserTeacherEntity> userTeacherList = userTeacherService.list();
		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		if (CollectionUtil.isNotEmpty(userTeacherList)){
			List<Long> teacherIds = userTeacherList.stream().map(UserTeacherEntity::getUserId).collect(Collectors.toList());
			lambdaQueryWrapper.notIn(User::getId,teacherIds);
		}

		//搜索处理
		if (StringUtils.isNotBlank(user.getRealName())) {
			lambdaQueryWrapper.like(User::getRealName, user.getRealName());
		}

		if (StringUtils.isNotBlank(user.getAccount())) {
			lambdaQueryWrapper.like(User::getAccount, user.getAccount());
		}

		IPage<User> pages = userService.page(Condition.getPage(query), lambdaQueryWrapper);

		IPage<UserVO> userVOIPage = UserWrapper.build().pageVO(pages);
		userVOIPage.getRecords().forEach(userVo -> {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserId(userVo.getId());
			if (null != userBaseEntity) {
				userVo.setIdCard(userBaseEntity.getUserNumber());
				userVo.setUserName(userBaseEntity.getUserName());
				userVo.setTrainingMajorCategory(userBaseEntity.getTrainingMajorCategory());
				userVo.setTrainingMajorDirection(userBaseEntity.getTrainingMajorDirection());
				userVo.setAppointmentGrade(userBaseEntity.getAppointmentGrade());
				userVo.setRemark(userBaseEntity.getRemark());

			}
		});
		return R.data(userVOIPage);
	}


	@PostMapping("/save-teacher")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "保存教师", notes = "传入account和realName")
	@Transactional(rollbackFor = Exception.class)
	public R saveTeacher(@RequestBody @Valid UserVO user) {
		if (StringUtils.isBlank(user.getRoleId())) throw new TrainingServiceException("请选择角色");
		if (CollectionUtil.isEmpty(user.getUserIds())) throw new TrainingServiceException("请选择用户");

		List<User> userList = user.getUserIds().stream().map(userId -> {
			User userById = userService.getById(userId);
			if (StringUtils.isNotBlank(userById.getRoleId()))
				userById.setRoleId(userById.getRoleId() + "," + user.getRoleId());
			else userById.setRoleId(user.getRoleId());
			//保存教师
			UserTeacherEntity userTeacherEntity=userTeacherService.selectByUserId(userId);
			if (null==userTeacherEntity){
				userTeacherEntity=new UserTeacherEntity();
				userTeacherEntity.setUserId(userId);
				userTeacherEntity.setTeacherId(userId);
				userTeacherService.save(userTeacherEntity);
			}
			return userById;
		}).collect(Collectors.toList());

		userService.updateBatchById(userList);
		return R.success("保存成功");
	}

}
